<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */

declare (strict_types=1);

namespace app\jobproject\controller;

use app\base\BaseController;
use app\busine\model\LicenseOutside;
use app\busine\model\LicenseOutsideCert;
use app\license\model\License;
use app\license\model\LicenseCert;
use app\license\model\LicenseProject;
use think\facade\Db;
use think\facade\View;

class Busine extends BaseController
{

    public function index()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = array();
            $whereOr = array();
            if (!empty($param['keywords'])) {
                $where[] = ['a.license_name', 'like', '%' . $param['keywords'] . '%'];
            }
            if ($this->uid > 3) {
                $where[] = ['a.project_user_id', '=', $this->uid];
            }
            $where[] = ['a.sign_state', '=', 0];
            $where[] = ['a.delete_time', '=', 0];
            $where[] = ['a.check_status', '=', 2];
            $model = new LicenseCert();
            $list = $model->get_project_list($param, $where, $whereOr);
            return table_assign(0, '', $list);
        } else {

            $param = get_params();
            $id = isset($param['id']) ? $param['id'] : 0;
            View::assign('id', $id);
            View::assign('uid', $this->uid);
            return view();
        }

    }

    //查看
    public function view()
    {
        $param = get_params();

        if (request()->isAjax()) {

        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            View::assign('id', $id);

            $licenModel = new LicenseCert();
            $licen = $licenModel->detail($id);
            $certs = Db::name('license_cert_cates')->whereIn('cert_id', $id)->select()->toArray();
            $str = '';
            $cert_types = [];
            foreach ($certs as $k => $v) {
                if ($str == '') {
                    $str .= $v['cert_serial'] . '-' . $v['cert_from'] . '-' . $v['cert_level'];
                } else {
                    $str .= '|' . $v['cert_serial'] . '-' . $v['cert_from'] . '-' . $v['cert_level'];
                }
                $cert_types[] = $v['cert_from_type'];
            }
            $cert_types = implode('|', array_unique($cert_types));
            $licen->cert_types = $cert_types;
            $licen->projects = $str;
            View::assign('licen', $licen);


            $model = new LicenseProject();
            $detail = $model->where(['cert_id' => $id])->find();
            if (!empty($detail)) {
                $detail->status_name = LicenseProject::$Status[(int)$detail['check_status']];
                $detail->create_user = Db::name('Admin')->where(['id' => $detail['admin_id']])->value('name');
                $flows = Db::name('FlowStep')->where(['action_id' => $detail['id'], 'type' => 18, 'sort' => $detail['check_step_sort'], 'delete_time' => 0])->find();
                $detail['check_user'] = '-';
                $detail['copy_user'] = '-';
                $check_user_ids = [];
                if ($detail['check_status'] == 1) {
                    if ($flows['flow_type'] == 1) {
                        $detail['check_user'] = '部门负责人';
                        $check_user_ids[] = get_department_leader($detail['admin_id']);
                    } else if ($flows['flow_type'] == 2) {
                        $detail['check_user'] = '上级部门负责人';
                        $check_user_ids[] = get_department_leader($detail['admin_id'], 1);
                    } else {
                        $check_user_ids = explode(',', $flows['flow_uids']);
                        $check_user = Db::name('Admin')->where('id', 'in', $flows['flow_uids'])->column('name');
                        $detail['check_user'] = implode(',', $check_user);
                    }
                }

                if ($detail['copy_uids'] != '') {
                    $copy_user = Db::name('Admin')->where('id', 'in', $detail['copy_uids'])->column('name');
                    $detail['copy_user'] = implode(',', $copy_user);
                }
                $is_check_admin = 0;
                $is_create_admin = 0;
                if ($detail['admin_id'] == $this->uid) {
                    $is_create_admin = 1;
                }
                if (in_array($this->uid, $check_user_ids)) {
                    $is_check_admin = 1;
                    //当前审核节点详情
                    if ($flows['flow_type'] == 4) {
                        $check_count = Db::name('FlowRecord')->where(['action_id' => $detail['id'], 'type' => 18, 'step_id' => $flows['id'], 'check_user_id' => $this->uid])->count();
                        if ($check_count > 0) {
                            $is_check_admin = 0;
                        }
                    }
                }

                $check_record = Db::name('FlowRecord')->field('f.*,a.name,a.thumb')
                    ->alias('f')
                    ->join('Admin a', 'a.id = f.check_user_id', 'left')
                    ->where(['f.action_id' => $detail['id'], 'f.type' => 18])
                    ->order('check_time desc')
                    ->select()->toArray();
                foreach ($check_record as $kk => &$vv) {
                    $vv['check_time_str'] = date('Y-m-d H:i', $vv['check_time']);
                    $vv['status_str'] = '提交';
                    if ($vv['status'] == 1) {
                        $vv['status_str'] = '审核通过';
                    } else if ($vv['status'] == 2) {
                        $vv['status_str'] = '审核拒绝';
                    }
                    if ($vv['status'] == 3) {
                        $vv['status_str'] = '撤销';
                    }
                }

                View::assign('is_create_admin', $is_create_admin);
                View::assign('is_check_admin', $is_check_admin);
                View::assign('check_record', $check_record);
                View::assign('flows', $flows);
                View::assign('uid', $this->uid);
                View::assign('detail', $detail);
                View::assign('is_report', 1);
            }else{
                View::assign('is_report', 0);
            }

            return view();
        }
    }

    //添加&&编辑
    public function report_add()
    {
        $param = get_params();
        unset($param['file']);
        unset($param['scene']);

        if (empty($param['report_date'])) {
            unset($param['report_date']);
        }
        if (request()->isAjax()) {
            $report_status = $param['report_status'] ?? '';
            $cert_id = $param['cert_id'] ?? '';
            $deduct = $param['deduct'] ?? '';
            unset($param['cert_id']);
            if ($report_status == 3 && $deduct == '') {
                return to_assign(1, '请填写提成金额');
            }
            $cert = Db::name('license_cert')->where(['id' => $cert_id])->find();
            $license_id = $cert['license_id'] ?? '';
            if ($license_id) {
                Db::name('license')->where('id', $license_id)->update(['check_status' => $report_status]);
            }
            $project = Db::name('license_project')->where(['cert_id' => $cert_id])->find();
            if (!empty($project)) {
                $param['update_time'] = time();
                $res = Db::name('license_project')->where(['cert_id' => $cert_id])->update($param);
                if ($res) {
                    add_log('edit', $cert_id, $param);
                    return to_assign();
                } else {
                    return to_assign(1, '操作失败');
                }
            } else {
                $param['license_id'] = $cert['license_id'] ?? 0;
                $param['license_name'] = $cert['license_name'] ?? '';
                $param['cert_id'] = $cert_id;
                $param['admin_id'] = $this->uid;
                $param['create_time'] = time();
                $res = Db::name('license_project')->insertGetId($param);
                if ($res) {
                    add_log('add', $res, $param);
                    return to_assign();
                } else {
                    return to_assign(1, '操作失败');
                }
            }
        } else {
            $cert_id = isset($param['cert_id']) ? $param['cert_id'] : 0;
            View::assign('cert_id', $cert_id);
            if ($cert_id > 0) {
                $model = new LicenseCert();
                $detail = $model->detail($cert_id);
                $project = Db::name('license_project')->where(['cert_id' => $cert_id])->find();
                $detail->report_date = $project['report_date'];
                $detail->report_name = $project['report_name'];
                $detail->report_num = $project['report_num'];
                $detail->report_status = $project['report_status'];
                $detail->deduct = $project['deduct'];
                $detail->gs_date = $project['gs_date'];
                $detail->report_id = $project['report_id'];
                View::assign('detail', $detail);
            }
            return view();
        }
    }


    public function fenpei()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $id = isset($param['id']) ? $param['id'] : 0;
            $project_user_id = isset($param['project_user_id']) ? $param['project_user_id'] : 0;
            $data['id'] = $id;
            $data['project_user_id'] = $project_user_id;
            if (Db::name('license_cert')->update($data) !== false) {
                return to_assign(0, "分配成功");
            } else {
                return to_assign(1, "分配失败");
            }

        } else {
            $cert_id = isset($param['cert_id']) ? $param['cert_id'] : 0;
            View::assign('cert_id', $cert_id);
            if ($cert_id > 0) {
                $model = new LicenseCert();
                $detail = $model->detail($cert_id);
                View::assign('detail', $detail);
            }
            return view();
        }
    }

    //添加&&编辑
    public function project_add()
    {
        $param = get_params();
        unset($param['file']);
        unset($param['scene']);


        if (request()->isAjax()) {
            $check_crets = $param['check_crets'] ?? [];
            if (empty($check_crets)) {
                return to_assign(1, '请先保存资质类型');
            }
            unset($param['check_crets']);
            $param['admin_id'] = $this->uid;
            $param['check_status'] = 2;
            $param['is_self'] = 1;
            if (!empty($param['id']) && $param['id'] > 0) {
                $param['update_time'] = time();
                $res = Db::name('license_cert')->where(['id' => $param['id']])->update($param);
                if ($res) {
                    Db::name('license_cert_cates')->where('cert_id', $param['id'])->delete();
                    if (!empty($check_crets)) {
                        $certs_all = [];
                        foreach ($check_crets as $k => $v) {
                            $certs = [];
                            list($a, $b, $c, $d) = explode('|', $v);
                            $certs['cert_serial'] = $a;
                            $certs['cert_from'] = $b;
                            $certs['cert_level'] = $c;
                            $certs['cert_from_type'] = $d;
                            $certs['cert_id'] = $param['id'];
                            $certs_all[] = $certs;
                        }
                        Db::name('license_cert_cates')->insertAll($certs_all);
                    }

                    add_log('edit', $param['id'], $param);
                    return to_assign();
                } else {
                    return to_assign(1, '操作失败');
                }
            } else {
                $param['create_time'] = time();
                $param['admin_id'] = $this->uid;
                $aid = Db::name('license_cert')->insertGetId($param);
                if ($aid) {
                    if (!empty($check_crets)) {
                        $certs_all = [];
                        foreach ($check_crets as $k => $v) {
                            $certs = [];
                            list($a, $b, $c, $d) = explode('|', $v);
                            $certs['cert_serial'] = $a;
                            $certs['cert_from'] = $b;
                            $certs['cert_level'] = $c;
                            $certs['cert_from_type'] = $d;
                            $certs['cert_id'] = $aid;
                            $certs_all[] = $certs;
                        }
                        Db::name('license_cert_cates')->insertAll($certs_all);
                    }

                    add_log('add', $aid, $param);
                    return to_assign();
                } else {
                    return to_assign(1, '操作失败');
                }
            }
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            View::assign('id', $id);
            $cert_id = isset($param['cert_id']) ? $param['cert_id'] : 0;
            View::assign('cert_id', $cert_id);
            if ($id > 0) {
                $model = new LicenseCert();
                $detail = $model->detail($id);
                $detail->cert_cates = Db::name('license_cert_cates')->where('cert_id', $id)->select()->toArray();
                View::assign('detail', $detail);
            }
            return view();
        }
    }

    public function project_report()
    {
        $param = get_params();
        if (request()->isAjax()) {

            $param['check_status'] = 1;
            $param['check_step_sort'] = 0;
            $flow_list = Db::name('Flow')->where('id', $param['flow_id'])->value('flow_list');
            $flow = unserialize($flow_list);
            //删除原来的审核流程和审核记录
            Db::name('FlowStep')->where(['action_id' => $param['id'], 'type' => 18, 'delete_time' => 0])->update(['delete_time' => time()]);
            Db::name('FlowRecord')->where(['action_id' => $param['id'], 'type' => 18, 'delete_time' => 0])->update(['delete_time' => time()]);
            if (!isset($param['check_admin_ids'])) {
                if ($flow[0]['flow_type'] == 1) {
                    //部门负责人
                    $leader = get_department_leader($this->uid);
                    if ($leader == 0) {
                        return to_assign(1, '审批流程设置有问题：当前部门负责人还未设置，请联系HR或者管理员');
                    } else {
                        $param['check_admin_ids'] = $leader;
                    }
                } else if ($flow[0]['flow_type'] == 2) {
                    //上级部门负责人
                    $leader = get_department_leader($this->uid, 1);
                    if ($leader == 0) {
                        return to_assign(1, '审批流程设置有问题：上级部门负责人还未设置，请联系HR或者管理员');
                    } else {
                        $param['check_admin_ids'] = $leader;
                    }
                } else {
                    $param['check_admin_ids'] = $flow[0]['flow_uids'];
                }
                foreach ($flow as $key => &$value) {
                    $value['action_id'] = $param['id'];
                    $value['sort'] = $key;
                    $value['type'] = 18;
                    $value['create_time'] = time();
                }
                //增加审核流程
                Db::name('FlowStep')->strict(false)->field(true)->insertAll($flow);
            } else {
                $flow_step = array(
                    'action_id' => $param['id'],
                    'type' => 18,
                    'flow_uids' => $param['check_admin_ids'],
                    'create_time' => time()
                );
                //增加审核流程
                Db::name('FlowStep')->strict(false)->field(true)->insertGetId($flow_step);
            }

            $res = Db::name('license_project')->where('id', $param['id'])->strict(false)->field(true)->update($param);
            if ($res !== false) {
                $appro['action_id'] = $param['id'];
                $appro['type'] = 35;
                $appro['start_time'] = time();
                $appro['admin_id'] = $this->uid;
                $appro['department_id'] = $this->did;
                $appro['create_time'] = time();
                $appro['flow_id'] = $param['flow_id'];
                $appro['check_admin_ids'] = $param['check_admin_ids'];
                $appro['copy_uids'] = $param['copy_uids'];
                $appro['check_status'] = $param['check_status'];
                if(empty(Db::name('Approve')->where('action_id', $appro['action_id'])->where('type',$appro['type'])->find())){
                    Db::name('Approve')->strict(false)->field(true)->insertGetId($appro);
                }else{
                    Db::name('Approve')->where('action_id', $appro['action_id'])->where('type',$appro['type'])->strict(false)->field(true)->update($appro);
                }
                //添加提交申请记录
                $checkData = array(
                    'action_id' => $param['id'],
                    'check_user_id' => $this->uid,
                    'content' => '重新提交申请',
                    'type' => 18,
                    'check_time' => time(),
                    'create_time' => time()
                );
                $record_id = Db::name('FlowRecord')->strict(false)->field(true)->insertGetId($checkData);
                add_log('edit', $param['id'], $param);
                //发送消息通知
                $msg = [
                    'from_uid' => $this->uid,
                    'title' => '项目-资质上报',
                    'action_id' => $param['id']
                ];
                $users = $param['check_admin_ids'];
                sendMessage($users, 191, $msg);
                return to_assign();
            } else {
                return to_assign(1, '操作失败');
            }
        } else {
            $id = isset($param['cert_id']) ? $param['cert_id'] : 0;
            $department = $this->did;
            //获取发票审批流程
            $flows = get_type_department_flows(18, $department);
            View::assign('user', get_admin($this->uid));
            View::assign('flows', $flows);
            if ($id > 0) {
                $model = new LicenseProject();
                $detail = $model->where(['cert_id' => $id])->find();
                $detail['create_user'] = Db::name('Admin')->where(['id' => $detail['admin_id']])->value('name');
                $detail['status_name'] = LicenseProject::$Status[(int)$detail['check_status']];
                View::assign('detail', $detail);
            }
            return view();
        }
    }

}
